package org.freedoit.dao;
import java.io.File;
import java.io.FileFilter;
import java.text.MessageFormat;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import org.freedoit.FreeDoitConfig;
import org.freedoit.util.LogUtils;

public class DAOFactory {
    private static final Logger logger = LogUtils.getLogger(DAOFactory.class); 
    // For multiple thread issue, no lazy load here
	private static ProjectDAO projectDAO= new ProjectDAO();
	private static TaskDAO taskDAO = new TaskDAO();
	private static TaskTypeDAO taskTypeDAO = new TaskTypeDAO();
    private static SyncKeyDAO syncKeyDAO = new SyncKeyDAO();
	
    private static final String DB_DIR = FreeDoitConfig.getConfigDir() + "/db";
	private static final String EMF_NAME = DB_DIR + "/{0}/doit.odb";
    
    private static String userName;
	
	private static EntityManagerFactory pmfInstance;

	static EntityManagerFactory getEntityManagerFactory() {
        if (userName == null) {
            throw new RuntimeException("User cannot be empty");
        }

		if (pmfInstance == null) {
			pmfInstance = Persistence.createEntityManagerFactory(
                    MessageFormat.format(EMF_NAME, userName));
		}
		
		return pmfInstance;
	}
    
    private static void reset(String userName) {
        if (pmfInstance != null) {
            try {
                pmfInstance.close();
            } catch (Exception e) {
                logger.warn(e);
            }
        
            pmfInstance = null;
        }
        DAOFactory.userName = userName;
    }
    
    public static boolean userNameExist(final String userName) {
        if (userName == null) {
            return false;
        }
        File file = new File(DB_DIR);
        if (file.exists() && file.canRead()) {
            File[] fileTarget = file.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.isDirectory() && userName.equals(pathname.getName());
                }
                
            });
            
            return (fileTarget != null) && (fileTarget.length > 0);
        } else {
            return false;
        }
    }
    
    public static void switchUser(String userName) {
        if (userName == null || "".equals((userName = userName.trim())) 
                || userName.equals(DAOFactory.userName)) {
            return;
        }
        
        reset(userName);
    }

	public static ProjectDAO getProjectDAO() {
		return projectDAO;
	}

	public static TaskDAO getTaskDAO() {
		return taskDAO;
	}

	public static TaskTypeDAO getTaskTypeDAO() {
		return taskTypeDAO;
	}

	public static SyncKeyDAO getSyncKeyDAO() {
		return syncKeyDAO;
	}
}
